package com.custom.base.view

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Color
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.LinearLayout
import android.widget.TextView
import com.custom.base.R
import com.custom.base.databinding.ViewSelectBinding
import com.custom.base.databinding.ViewSelectTvBinding
import com.custom.base.util.SDViewUtil

/**
 * 作者：
 * 日期：2020/12/26
 * 说明：选择控件
 */
class SelectView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
    private var clickListener: OnSelectClickListener? = null
    private var selectViewColor = 0
    private var noSelectViewColor = 0
    private var selectTvColor = 0
    private var noSelectTvColor = 0
    private var selectTvSize = 0f
    private var noSelectTvSize = 0f
    private var bold = false //是否粗体
    private var isView = true //是否显示底部view
    private var isAverage = false //是否平均分
    private var isUpdate = true //是否点击的时候更新界面
    private var index = 0 //初始位置
    //private var textViews = mutableListOf<View>() //tab数据
    private var textViews = mutableListOf<TextView>() //tab数据

    private var btView: View? = null
    private var lastIndex = 0
    private var animationStart = 0f
    private var animationEnd = 0f
    private var viewWidth = arrayListOf<Int>()

    private var viewSelectBinding: ViewSelectBinding? = null
    private var viewSelectTvBinding: ViewSelectTvBinding? = null

    init {
        val selectAttrs: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.SelectView)
        val texts = selectAttrs.getString(R.styleable.SelectView_SelectView_tabs).toString()
        val bgColor = selectAttrs.getColor(
            R.styleable.SelectView_SelectView_bgColor,
            Color.parseColor("#FFFFFF")
        )
        selectViewColor = selectAttrs.getColor(
            R.styleable.SelectView_SelectView_selectViewColor,
            Color.parseColor("#FFFFA200")
        )
        noSelectViewColor = selectAttrs.getColor(
            R.styleable.SelectView_SelectView_noSelectViewColor,
            Color.parseColor("#00000000")
        )
        selectTvColor = selectAttrs.getColor(
            R.styleable.SelectView_SelectView_selectTvColor,
            Color.parseColor("#FF1677FF")
        )
        noSelectTvColor = selectAttrs.getColor(
            R.styleable.SelectView_SelectView_noSelectTvColor,
            Color.parseColor("#333333")
        )
        selectTvSize = selectAttrs.getDimension(R.styleable.SelectView_SelectView_selectTvSize, 16f)
        noSelectTvSize =
            selectAttrs.getDimension(R.styleable.SelectView_SelectView_noSelectTvSize, 16f)
        bold = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_bold, false)
        isView = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_isView, true)
        isAverage = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_isAverage, false)
        isUpdate = selectAttrs.getBoolean(R.styleable.SelectView_SelectView_isUpdate, true)

        if (!isView) {
            gravity = Gravity.CENTER_VERTICAL
        }

        setBackgroundColor(bgColor)

        if (texts != "null") {
            setTabText(texts.split(","))
            upDate()
        }
    }

    /**
     * 计算移动终点的只
     */
    private fun cha(zhi: Int = 0, i: Int = lastIndex): Float {
        var z = zhi
        z += if (i == lastIndex || i == index) viewWidth[i] / 2
        else viewWidth[i]
        return when {
            i != index -> cha(z, if (index > lastIndex) i + 1 else i - 1)
            index > lastIndex -> animationStart + z.toFloat()
            else -> animationStart - z.toFloat()
        }
    }

    /**
     * 更新滑块位置
     */
    private fun updateSlider() {
        btView?.apply {
            if (viewWidth.size > 0) {
                animationStart = animationEnd
                animationEnd = cha()
                val translateAnimation: Animation =
                    TranslateAnimation(animationStart, animationEnd, 0f, 0f) //设置平移的起点和终点
                translateAnimation.duration = 200 //动画持续的时间
                translateAnimation.isFillEnabled = true //使其可以填充效果从而不回到原地
                translateAnimation.fillAfter = true //不回到起始位置
                //如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
                animation = translateAnimation //给imageView添加的动画效果
                translateAnimation.startNow() //动画开始执行 放在最后即可
                lastIndex = index
            }
        }
    }

    /**
     * 设置tab数据
     */
    fun setTabText(split: List<String>) {
        //val view = SDViewUtil.getRId(R.layout.view_select)
        viewSelectBinding = ViewSelectBinding.inflate(LayoutInflater.from(context))
        if (isView) btView = viewSelectBinding?.viewSelectView
        else viewSelectBinding?.viewSelectView?.visibility = View.GONE
        if (isAverage) viewSelectBinding?.viewSelectLl?.let { SDViewUtil.setViewWidthMatchParent(it) }
        else viewSelectBinding?.viewSelectLl?.let { SDViewUtil.setViewWidthWrapContent(it) }
        for (i in split.indices) {
            //val tvView = SDViewUtil.getRId(R.layout.view_select_tv)
            viewSelectTvBinding = ViewSelectTvBinding.inflate(LayoutInflater.from(context))
            viewSelectTvBinding?.viewSelectTv?.gravity = Gravity.CENTER
            viewSelectTvBinding?.viewSelectTv?.text = split[i]
            viewSelectTvBinding?.root?.setOnClickListener {
                if (index != i) {
                    index = i
                    clickListener?.onSelect(i)
                    if (isUpdate) upDate()
                }
            }
            if (isAverage) viewSelectBinding?.viewSelectLl?.addView(
                viewSelectTvBinding?.root,
                LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)
            )
            else viewSelectBinding?.viewSelectLl?.addView(viewSelectTvBinding?.root)
            viewSelectTvBinding?.viewSelectTv?.let { textViews.add(it) }
        }
        addView(viewSelectBinding?.root, SDViewUtil.layoutParamsLinearLayoutMW)
        if (isView) SDViewUtil.getViewSize(
            viewSelectBinding?.viewSelectView,
            true,
            200,
            object : SDViewUtil.SDViewSizeListener {
                override fun onResult(v: View) {
                    textViews.forEach {
                        viewWidth.add(SDViewUtil.getViewWidth(it))
                    }
                    if (viewWidth.size > 0) viewSelectBinding?.viewSelectView?.let {
                        SDViewUtil.setViewMarginLeft(
                            it,
                            viewWidth[0] / 2 - v.width / 2
                        )
                    }
                }
            })
    }

    /**
     * 开始更新UI
     */
    fun start() {
        upDate()
    }

    /**
     * 改变选中位置
     */
    fun setIndex(i: Int) {
        index = i
        upDate()
    }

    /**
     * 更新UI
     */
    private fun upDate() {
        updateSlider()
        for (i in textViews.indices) {
            val tv = textViews[i]
            if (index == i) {
                tv.setTextColor(selectTvColor)
                tv.textSize = selectTvSize
                tv.typeface =
                    Typeface.defaultFromStyle(if (bold) Typeface.BOLD else Typeface.NORMAL)
            } else {
                tv.setTextColor(noSelectTvColor)
                tv.textSize = noSelectTvSize
                tv.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
            }
        }
    }

    /**
     * 设置点击事件
     */
    fun setClickListener(listener: OnSelectClickListener): SelectView {
        this.clickListener = listener
        return this
    }

    interface OnSelectClickListener {
        fun onSelect(index: Int)
    }

    /**
     * 获取数据数量
     */
    fun getDataSize(): Int {
        return textViews.size
    }

    /**
     * 获取初始位置
     */
    fun getIndex(): Int {
        return index
    }


    fun getViewWidth(): ArrayList<Int> {
        return viewWidth
    }

    fun setViewWidth(viewWidth: ArrayList<Int>) {
        this.viewWidth = viewWidth
    }
}